#include <iostream>
 
#include <stdio.h>
#include <stdlib.h>
 
#include <sys/socket.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>
 
using namespace std;
 
#define MAXLINE 1024
#define SERVER_PORT 10004


int main() {
	// socket client init
	char addr[] = "127.0.0.1";
	char* servInetAddr = addr;
//	char* servInetAddr = "127.0.0.1";
	int socketfd;
	struct sockaddr_in sockaddr;
	char recvline[MAXLINE], sendline[MAXLINE];
 
	//原型 int socket(int domain, int type, int protocol)
	//domain表示要使用的协议簇，AF_UNIX（本机通信）AF_INET(TCP/IP - IPv4) AF_INET(IPv6)
	//type参数指的是套接字类型 ：SOCK_STREAM(TCP流) SOCK_DGRAM(UDP数据报) SOCK_RAW(原始套接字)
	//如果前两个参数确定了那么protocol参数设置为0
	//如果创建成功则返回套接字，失败则返回-1,并且错误代码写入errno
	socketfd = socket(AF_INET, SOCK_STREAM, 0);
 
	memset(&sockaddr, 0, sizeof(sockaddr));    //memset from string.h
	sockaddr.sin_family = AF_INET;    //sin_family from netinet/in.h
	sockaddr.sin_port = htons(10004);
	inet_pton(AF_INET, servInetAddr, &sockaddr.sin_addr);  // inet_pton from arpa/inet.h
	if((connect(socketfd, (struct sockaddr*) &sockaddr, sizeof(sockaddr)))<0){   //连接到服务器
		printf("connect error %s errno: %d\n", strerror(errno),errno);
		exit(0);
	}
	printf("连接到服务器...\n");
	//end socket client init
 
	while(1){
		printf("发送消息...\n");
		scanf("%s", sendline);
//		strcpy(sendline, "hello");
		if((send(socketfd, sendline, strlen(sendline), 0))<0){
			printf("send message error: %s errno : %d", strerror(errno), errno);
			exit(0);
		}else{
			printf("send message to server successful\n");
		}
		if(strcmp(sendline, "quit")==0){
			break;
		}
		int bytesReceived = 0;
		bytesReceived = recv(socketfd, recvline, MAXLINE, 0);
		string RespStr = recvline;
		RespStr = RespStr.substr(0,bytesReceived);
		cout<<"recv msg from server:"+RespStr<<endl;
	}
	close(socketfd);
 
	return 0;
}